 package com.lfk.justwetools.Component.Proportionview;

import ohos.agp.render.BlendMode;
import ohos.agp.render.Path;
import ohos.app.Context;
import ohos.agp.render.Canvas;
import ohos.agp.utils.Color;
import ohos.agp.render.Paint;
import ohos.agp.utils.RectFloat;
import ohos.agp.components.AttrSet;
import ohos.multimodalinput.event.TouchEvent;
import ohos.agp.components.Component;

import java.util.TreeMap;

public class ProportionView extends Component implements Component.DrawTask, Component.TouchEventListener {
    private int ColorSet[] = {0xFFFEDD74,  0xFF82D8EF, 0xFFF76864, 0xFF80BD91, 0xFFFD9FC1, 0xFF};
    private float totalSize = 0;
    private Paint paint = new Paint();
    private Path border = new Path();
    private RectFloat rect = new RectFloat();
    private TreeMap<String, Long> map = null;

    public ProportionView(Context context) {
        this(context, null);
    }

    public ProportionView(Context context, AttrSet attrSet) {
        this(context, attrSet, null);
    }

    public ProportionView(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        addDrawTask(this);
        setTouchEventListener(this);
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        //获取长宽
        int width = this.getWidth();
        int height = this.getHeight();

        //设置画笔消除锯齿
        paint.setAntiAlias(false);

        //剪切底层模板形状
        rect.modify(0, 0, width, height);
        border.addRoundRect(rect, 40, 40, Path.Direction.COUNTER_CLOCK_WISE);
//        canvas.clipPath(border, Region.Op.REPLACE); // TODO: HOS does not support REPLACE Op.

        //背景色
        canvas.drawColor(Color.LTGRAY.getValue(), BlendMode.SRC);

        if(map != null && !map.isEmpty()) {
            //获取总大小
            totalSize = 0;
            for (String key : map.keySet()) {
                totalSize += map.get(key);
            }

            //设置色块
            int offset = 0;
            int colorOffset = 0;
            for (String key : map.keySet()) {
                paint.setColor(new Color(ColorSet[colorOffset++ % ColorSet.length]));
                canvas.drawRect(offset, 0, offset += (float) width * (float) map.get(key) / totalSize, height, paint);
            }
        }
    }

    public void setData(TreeMap<String, Long> data) {
        map = data;
        invalidate();
    }

    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
        return false;
    }
}